<template>
  <div class="home">
    <div class="imgFiles">
      <h2 style="text-align: center; margin: 20px 0">选择您的图片,限制六张</h2>
      <div style="text-align: center">
        <el-upload
          multiple
          action="#"
          :http-request="submitUpload"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :before-upload="beforeAvatarUpload"
          :auto-upload="false"
          :limit="6"
          :on-exceed="handleExceed"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </div>
    </div>
    <h2 style="text-align: center">请输入您的姓名</h2>
    <div style="width: 280px; margin: 20px auto">
      <el-input
        class="title"
        placeholder="请输入内容"
        v-model="input"
        clearable
        maxlength="15"
        show-word-limit
      >
      </el-input>
    </div>
    <div style="text-align: center">
      <el-button
        style="margin: 20px 0; width: 200px"
        type="success"
        @click="finish"
        :disabled="isUploadIng"
        >{{ uploadMsg }}</el-button
      >
    </div>
  </div>
</template>

<script>
import { request } from "@/network/request";

import Compressor from "compressorjs";

export default {
  name: "Home",
  data() {
    return {
      input: "",
      dialogImageUrl: [],
      dialogVisible: false,
      formData: "",
      uploadMsg: "开始上传",
      isUploadIng: false,
      fileListData: [],
      fileArr: [],
    };
  },
  methods: {
    compress(fileObj, callback) {
      let _this = this;
      try {
        const image = new Image();
        image.src = URL.createObjectURL(fileObj);
        image.onload = function () {
          const that = this;
          // 默认按比例压缩
          let w = that.width;
          let h = that.height;
          const scale = w / h;
          w = fileObj.width || w;
          h = fileObj.height || w / scale;
          let quality = 0.1; // 默认图片质量为0.7
          // 生成canvas
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");
          // 创建属性节点
          const anw = document.createAttribute("width");
          anw.nodeValue = w;
          const anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(that, 0, 0, w, h);
          // 图像质量
          if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
            quality = fileObj.quality;
          }
          // quality值越小，所绘制出的图像越模糊
          const data = canvas.toDataURL("image/jpeg", quality);
          // 压缩完成执行回调
          const newFile = _this.convertBase64UrlToBlob(data);
          callback(newFile);
        };
      } catch (e) {
        console.log("压缩失败!");
      }
    },
    convertBase64UrlToBlob(urlData) {
      const bytes = window.atob(urlData.split(",")[1]); // 去掉url的头，并转换为byte
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], { type: "image/png" });
    },
    handleChange(file,fileList) {
      // this.$refs.upload.clearFiles();
      let _this = this;
      let obj = {
        imgUrl: "",
        name: "",
      };
      let item1 = file;
      this.compress(item1.raw, (val) => {
        let newfile = new window.File([val], file.name, { type: file.type });
        newfile.uid = file.uid;
        this.fileListData.push(newfile);
      });
      var Newfile = item1.raw;
      obj.name = item1.name;
      var reader = new FileReader();
      reader.onload = function (e) {
        //转base64
        obj.imgUrl = e.target.result;
        _this.fileArr.push(obj);
      };
      reader.readAsDataURL(Newfile);

      // this.$set(this.form, "fileList", fileListData);
      // console.log(this.form.fileList);
    },
    finish() {
      console.log("begin");
      if (this.input == "") {
        this.$message.error("姓名不能为空哦");
        return;
      }
      this.formData = new FormData();
      this.$refs.upload.submit();
      for (let i = 0; i < this.fileListData.length; i++) {
        this.formData.append("files", this.fileListData[i]);
      }
      this.formData.append("WS_CODE", "12133");
      this.formData.append("name", this.input);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      this.uploadMsg = "正在上传...";
      this.isUploadIng = true;
      request({
        method: "post",
        url: "/upload",
        data: this.formData,
        config,
      }).then((rest) => {
        console.log(rest);
        if (rest.data.reason == "上传成功") {
          this.$message({
            message: "您的图片已上传成功",
            type: "success",
          });
        } else {
          this.$message.error("未知错误，上传失败");
        }
        this.input = "";
        this.$refs.upload.clearFiles();
        this.uploadMsg = "开始上传";
        this.isUploadIng = false;
        this.fileListData=[]
        this.fileArr=[]
      }).catch(err=>{
        this.fileListData=[]
        this.fileArr=[]
      })
    },
    handleRemove(file, fileList) {
      this.dialogImageUrl = [];
      for (let i = 0; i < this.fileListData.length; i++) {
        if(this.fileListData[i].uid==file.uid){
          this.fileListData.splice(i,1)
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPEG && !isJPG && !isPNG) {
        this.$message.error(
          "上传头像图片只能是 JPG 格式 或者 JPEG 格式 或者 PNG 格式"
        );
      }
      if (!isLt10M) {
        this.$message.error("上传失败,图片大小不能超过 10MB!");
        this.input = "";
      }
      return (isJPG || isPNG || isJPEG) && isLt10M;
    },
    submitUpload(item) {
      
    },
    //实验抛弃的函数，留着用于研究base64压缩
    compress22(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      // 		铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //修复ios上传图片的时候 被旋转的问题
      if (Orientation != "" && Orientation != 1) {
        switch (Orientation) {
          case 6: //需要顺时针（向左）90度旋转
            this.rotateImg(img, "left", canvas);
            break;
          case 8: //需要逆时针（向右）90度旋转
            this.rotateImg(img, "right", canvas);
            break;
          case 3: //需要180度旋转
            this.rotateImg(img, "right", canvas); //转两次
            this.rotateImg(img, "right", canvas);
            break;
        }
      }
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);

      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log("ndata:" + ndata);

      console.log(
        "压缩率：" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;

      return ndata;
    },
  },
};
</script>
